package com.smartum.mpr.utils;

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.smartum.mpr.exception.UnsupportedImageFormat;

public class ImageUtil {

	public static BufferedImage resizeImageSavingAspection(File imageFile, int newWidth) throws IOException {
		BufferedImage originalImage = ImageIO.read(imageFile);
		int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
		int imageWidth = originalImage.getWidth();
		double scaleRate = (double) newWidth / (double) imageWidth;
		int newHeight = (int) (originalImage.getHeight() * scaleRate);

		BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, type);
		Graphics2D g = resizedImage.createGraphics();
		g.drawImage(originalImage, 0, 0, newWidth, newHeight, null);
		g.dispose();

		g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
		g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

		return resizedImage;
	}

	public static BufferedImage resizeImage(File imageFile, int newWidth, int newHeight) throws IOException {
		BufferedImage originalImage = ImageIO.read(imageFile);
		int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
		BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, type);
		Graphics2D g = resizedImage.createGraphics();
		g.drawImage(originalImage, 0, 0, newWidth, newHeight, null);
		g.dispose();

		g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
		g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

		return resizedImage;
	}

	public static String getImageFormat(String fileName) throws UnsupportedImageFormat {
		for (String format : ImageIO.getReaderFormatNames()) {
			if(fileName.endsWith(format)){
				return format;
			}
		}
		throw new UnsupportedImageFormat();
	}

	public static String addPostfixToPhotoWithSupportFileFormat(String fileName, String postfix) throws UnsupportedImageFormat {
		String format = getImageFormat(fileName);
		return fileName.replace(format, "") + postfix + "." + format;
	}

}
